package com.intelligentmeterreadingsys.waterbanding.activity;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.location.LocationManager;
import android.net.Uri;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.NfcV;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.intelligentmeterreadingsys.R;
import com.intelligentmeterreadingsys.httpserver.HttpClientServer;
import com.intelligentmeterreadingsys.httpserver.RequestUrl;
import com.intelligentmeterreadingsys.povo.UserWaterVO;
import com.intelligentmeterreadingsys.util.BluetoothHelp;
import com.intelligentmeterreadingsys.util.CHexConver;
import com.intelligentmeterreadingsys.util.DateUtil;
import com.intelligentmeterreadingsys.util.SharedPreferenceUtil;
import com.intelligentmeterreadingsys.util.TipHelper;
import com.intelligentmeterreadingsys.waterbanding.db.WaterBandingImpl;

import dbhelper.DbTableName;
import dbhelper.XmlNameHelper;

/**
 * 水表绑定
 * 
 * @author king
 * 
 */
public class WaterBandingActivity extends Activity implements OnClickListener, BDLocationListener {

    public Button button1;// 读卡按钮

    public Button button3;// 提交按钮

    public Button button6;// 上传按钮

    public TextView textview1;// 用户姓名

    public TextView textview4;// 水表编号
    public TextView textview5;// 水表地址
    public TextView textview6;// 水表径度
    public TextView textview7;// 水表维度
    public TextView textview8;// RFID卡号
    public EditText edit;
    public UserWaterVO list;
    public int i = 0;
    private final static int DIALOG = 1;

    public String xieyi = "15693";
    public long time;
    public String RFID;
    public Double latitude = 0.0;// 维度
    public Double longitude = 0.0;// 径度
    public ProgressDialog pd;
    public String imsi = "";
    public LocationClient client;// 定位对象

    public boolean issave = false;
    public static final int ITEM0 = Menu.FIRST;// 系统值
    public boolean isStop = true;
    public boolean isupload = false;

    public String readtype = "NFC读卡";

    public BluetoothHelp bluehelp;
    public String[] readdate;
    public boolean isbluetooth = true;
    public String[] date = null;
    public SharedPreferenceUtil sp;

    private NfcAdapter mAdapter;
    private PendingIntent mPendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;
    public boolean isNfc = false;

    public Dialog dialog = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

	super.onCreate(savedInstanceState);

	setContentView(R.layout.waterbanding);
	sp = new SharedPreferenceUtil(this);
	bluehelp = new BluetoothHelp(this);
	bluehelp.init();
	init();

	addDate();

    }

    /**
     * 初始化组件
     */
    public void init() {
	textview1 = (TextView) findViewById(R.id.waterbanding_username);
	edit = (EditText) findViewById(R.id.waterbanding_locationadds);
	textview4 = (TextView) findViewById(R.id.waterbanding_waternumber);
	textview5 = (TextView) findViewById(R.id.waterbanding_wateradds);
	textview6 = (TextView) findViewById(R.id.waterbanding_latitude);
	textview7 = (TextView) findViewById(R.id.waterbanding_longitude);
	textview8 = (TextView) findViewById(R.id.waterbanding_RFID);
	button1 = (Button) findViewById(R.id.waterbanding_readcard);

	button3 = (Button) findViewById(R.id.waterbanding_button);

	button6 = (Button) findViewById(R.id.waterbanding_upload);
	button6.setOnClickListener(this);
	button1.setOnClickListener(this);
	button3.setOnClickListener(this);

	WaterBandingImpl dao = new WaterBandingImpl(this);

	String id = getIntent().getStringExtra("waterid");
	this.list = dao.queryWaterInfo(id);

	addDate();
	isStop = false;

	dao.close();
	initlocation();
	SharedPreferenceUtil sp = new SharedPreferenceUtil(this);
	imsi = sp.getValue(XmlNameHelper.IMSI);
	mAdapter = NfcAdapter.getDefaultAdapter(WaterBandingActivity.this);

	mPendingIntent = PendingIntent.getActivity(WaterBandingActivity.this, 0, new Intent(WaterBandingActivity.this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
	IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
	try {
	    ndef.addDataType("*/*");
	    mFilters = new IntentFilter[] { ndef, };
	    mTechLists = new String[][] { new String[] { NfcV.class.getName() }, new String[] { MifareClassic.class.getName() } };

	} catch (MalformedMimeTypeException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}

    }

    @Override
    public void onClick(View v) {
	switch (v.getId()) {
	case R.id.waterbanding_readcard:

	    Date d = new Date();
	    time = d.getTime();
	    Toast.makeText(this, "读卡中", Toast.LENGTH_SHORT).show();

	    RFID = "";
	    if (readtype.equals("蓝牙读卡")) {
		isStop = true;
		isNfc = false;
		bluehelp.start();
		pd.dismiss();
	    } else {
		isNfc = true;
		isStop = false;
		return;
	    }

	    new Thread() {

		@Override
		public void run() {
		    while (isStop) {
			Date d = new Date();
			if (d.getTime() - time > 20000) {
			    isStop = false;
			    Message msg = MyHandler.obtainMessage();
			    msg.what = 2;
			    MyHandler.sendMessage(msg);
			}
			String id = bluehelp.getRfidId();

			if (!TextUtils.isEmpty(id)) {
			    isStop = false;
			    Message msg = MyHandler.obtainMessage();
			    msg.what = 1;
			    msg.obj = id;
			    MyHandler.sendMessage(msg);
			}
			try {
			    Thread.sleep(200);
			} catch (InterruptedException e) {

			    e.printStackTrace();
			}
		    }
		    super.run();
		}

	    }.start();
	    break;

	case R.id.waterbanding_button:
	    if (list == null) {
		Toast.makeText(WaterBandingActivity.this, "没水表不能绑定", 1000).show();
		return;
	    }
	    if (RFID == null || RFID.equals("")) {
		Toast.makeText(WaterBandingActivity.this, "没有读卡不能绑定", Toast.LENGTH_SHORT).show();
		return;
	    }
	    banding();
	    break;

	case R.id.waterbanding_upload:
	    WaterBandingImpl dao = new WaterBandingImpl(this);

	    this.list = dao.queryWaterInfo(list.getWaterid());
	    if (issave) {
		pd = new ProgressDialog(WaterBandingActivity.this);
		pd.setMessage("上传中....");
		pd.show();
		final HttpClientServer server = new HttpClientServer(this);
		new Thread() {

		    @Override
		    public void run() {

			Map<String, String> map = new HashMap<String, String>();
			map.put("waternumber", textview4.getText().toString());
			map.put("latitude", latitude + "");
			map.put("longitude", longitude + "");
			map.put("RFIDnumber", textview8.getText().toString());
			map.put("addr", list.getAdds());
			map.put("imsi", imsi);

			String respone = server.doPost(map, RequestUrl.BandingWater);
			System.out.println(respone);
			if (respone.equals("error")) {
			    Message msg = handle.obtainMessage();
			    msg.what = 1;
			    handle.sendMessage(msg);
			} else {
			    try {
				JSONObject json = new JSONObject(respone);
				String message = json.getString("message");
				if (message.equals("yes")) {
				    Message msg = handle.obtainMessage();
				    msg.what = 2;
				    handle.sendMessage(msg);
				} else {
				    Message msg = handle.obtainMessage();
				    msg.what = 3;
				    handle.sendMessage(msg);
				}
			    } catch (JSONException e) {
				Message msg = handle.obtainMessage();
				msg.what = 3;
				handle.sendMessage(msg);
			    }

			}
		    }

		}.start();
	    }

	    break;
	default:
	    break;
	}

    }

    /**
     * 添加数据
     */
    public void addDate() {
	textview1.setText("");
	edit.setText("");
	textview4.setText("");
	textview5.setText("");
	textview6.setText("纬度:");
	textview7.setText("经度:");
	textview8.setText("");
	this.RFID = "";
	this.latitude = 0.0;
	this.longitude = 0.0;
	if (list != null) {
	    UserWaterVO water = list;
	    textview1.setText(water.getName());
	    edit.setText(water.getAdds());
	    textview4.setText(water.getWaternumber());
	    textview5.setText(water.getWateradds());
	    textview6.setText("纬度:" + water.getLatitude() + "");
	    textview7.setText("经度:" + water.getLongitude() + "");
	    textview8.setText(water.getRFIDnumber());
	    this.RFID = water.getRFIDnumber();
	    this.latitude = water.getLatitude();
	    this.longitude = water.getLongitude();
	}
    }

    /**
     * 绑定、修改（定位，RFID卡）
     */
    public void banding() {
	WaterBandingImpl dao = new WaterBandingImpl(this);
	String waternumber = textview4.getText().toString().trim();

	if (TextUtils.isEmpty(waternumber)) {
	    Toast.makeText(WaterBandingActivity.this, "没有水表编号不能进行此操作", Toast.LENGTH_LONG).show();
	    return;

	}

	boolean b = dao.BandingRFID(list.getWaterid(), RFID, latitude, longitude, edit.getEditableText().toString());
	if (b) {
	    Toast.makeText(WaterBandingActivity.this, "操作成功", Toast.LENGTH_LONG).show();
	    this.list = dao.queryWaterInfo(list.getWaterid());

	    issave = true;
	} else {
	    Toast.makeText(WaterBandingActivity.this, "操作失败", Toast.LENGTH_LONG).show();
	}
	addDate();
	dao.close();
    }

    @Override
    protected void onDestroy() {

	this.i = 0;
	if (client != null && client.isStarted()) {
	    client.stop();
	}
	if (bluehelp != null) {
	    bluehelp.stop();
	}
	super.onDestroy();
    }

    public Handler MyHandler = new Handler() {

	@Override
	public void handleMessage(Message msg) {
	    if (msg.what == 1) {
		isStop = false;
		isNfc = false;
		TipHelper.Vibrate(WaterBandingActivity.this, 1000);
		textview8.setText(msg.obj.toString());
		WaterBandingImpl dao = new WaterBandingImpl(WaterBandingActivity.this);

		UserWaterVO user = dao.queryUserWater(msg.obj.toString());

		dao.close();
		if (readtype.equals("蓝牙读卡")) {
		    bluehelp.close();
		}
		if (user != null) {
		    Toast.makeText(WaterBandingActivity.this, "此RFID已绑定了水表", 1000).show();
		    list = user;

		    addDate();
		} else {
		    Toast.makeText(WaterBandingActivity.this, "此RFID卡还未绑定水表", 1000).show();
		}
		RFID = msg.obj.toString();
		client.start();
		isStop = false;

	    } else if (msg.what == 2) {

		client.start();
		isStop = false;
		Toast.makeText(WaterBandingActivity.this, "读卡超时", 1000).show();
		if (readtype.equals("蓝牙读卡")) {
		    bluehelp.close();
		}
		pd.dismiss();

	    }
	}

    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

	menu.add(0, ITEM0, 0, "短息通知");
	menu.add(0, ITEM0 + 1, 0, "RFID协议");

	menu.add(0, ITEM0 + 3, 0, "读卡方式");
	menu.findItem(ITEM0 + 1);
	return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
	if (item.getItemId() == ITEM0) {
	    if (list == null) {
		Toast.makeText(WaterBandingActivity.this, "没查到用户无法发送", Toast.LENGTH_LONG).show();
		return false;
	    }
	    Uri smsToUri = Uri.parse("smsto:");
	    Intent sendIntent = new Intent(Intent.ACTION_VIEW, smsToUri);
	    sendIntent.putExtra("address", list.getPhone()); // 电话号码，这行去掉的话，默认就没有电话
	    sendIntent.putExtra("sms_body", "尊敬的" + list.getName() + "用户:你的水表已绑定RFID卡");
	    sendIntent.setType("vnd.android-dir/mms-sms");
	    startActivity(sendIntent);
	    System.out.println("发短息");
	} else if (item.getItemId() == (ITEM0 + 1)) {
	    showDialog(DIALOG);
	    System.out.println("选择协议");
	} else if (item.getItemId() == (ITEM0 + 2)) {

	    showDialog(DIALOG + 1);
	} else if (item.getItemId() == (ITEM0 + 3)) {
	    showDialog(DIALOG + 2);
	}
	return super.onOptionsItemSelected(item);
    }

    @Override
    protected Dialog onCreateDialog(int id) {

	Dialog dialog = null;
	switch (id) {
	case DIALOG:
	    Builder builder = new android.app.AlertDialog.Builder(this);
	    // 设置对话框的图标
	    builder.setIcon(R.drawable.buttondraw);
	    // 设置对话框的标题
	    builder.setTitle("单选按钮对话框");
	    // 0: 默认第一个单选按钮被选中

	    builder.setSingleChoiceItems(R.array.hobby, 0, new android.content.DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
		    xieyi = getResources().getStringArray(R.array.hobby)[which];

		}
	    });

	    // 添加一个确定按钮
	    builder.setPositiveButton(" 确 定 ", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
		    if (xieyi.equals("15693")) {

			time = System.currentTimeMillis();
		    } else if (xieyi.equals("14443")) {
			time = System.currentTimeMillis();

		    }
		}
	    });
	    // 创建一个单选按钮对话框
	    dialog = builder.create();
	    break;

	case DIALOG + 2:
	    if (readtype.equals("NFC读卡")) {
		readdate = new String[] { "NFC读卡", "蓝牙读卡" };
	    } else {
		readdate = new String[] { "蓝牙读卡", "NFC读卡" };
	    }

	    builder = new android.app.AlertDialog.Builder(this);
	    // 设置对话框的图标
	    builder.setIcon(R.drawable.buttondraw);
	    // 设置对话框的标题
	    builder.setTitle("读卡方式选择");
	    // 0: 默认第一个单选按钮被选中

	    builder.setSingleChoiceItems(readdate, 0, new android.content.DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
		    readtype = readdate[which];

		}
	    });

	    // 添加一个确定按钮
	    builder.setPositiveButton(" 确 定 ", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {

		}
	    });
	    // 创建一个单选按钮对话框
	    dialog = builder.create();
	    break;
	}
	return dialog;
    }

    Handler handle = new Handler() {

	@Override
	public void handleMessage(Message msg) {
	    pd.dismiss();
	    if (msg.what == 1) {
		Toast.makeText(WaterBandingActivity.this, "网络错误", Toast.LENGTH_LONG).show();
	    } else if (msg.what == 2) {
		Toast.makeText(WaterBandingActivity.this, "上传成功", Toast.LENGTH_LONG).show();
		WaterBandingImpl dao = new WaterBandingImpl(WaterBandingActivity.this);
		ContentValues values = new ContentValues();
		values.put("bandingstatus", "1");
		dao.modify(list.getWaterid(), DbTableName.WATERINFO, values);
		dao.close();
		isupload = true;
	    } else if (msg.what == 3) {
		Toast.makeText(WaterBandingActivity.this, "上传失败", Toast.LENGTH_LONG).show();
	    }
	}

    };

    /**
     * 得到水表数据
     */
    public void queryWater() {
	i = 0;
	WaterBandingImpl dao = new WaterBandingImpl(this);

	this.list = dao.queryWaterInfo(list.getWaterid());
	addDate();
	dao.close();
    }

    @Override
    protected void onPause() {

	mAdapter.disableForegroundDispatch(this);

	super.onPause();
    }

    @Override
    protected void onResume() {
	mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);

	super.onResume();
    }

    @Override
    protected void onNewIntent(Intent intent) {
	if (!isNfc) {
	    return;
	}

	if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
	    Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
	    for (String tech : tagFromIntent.getTechList()) {
		System.out.println(tech);
	    }
	    time = System.currentTimeMillis();
	    MifareClassic mf = MifareClassic.get(tagFromIntent);
	    if (mf != null) {

		boolean auth = false;
		try {
		    mf.connect();
		    auth = mf.authenticateSectorWithKeyA(0, MifareClassic.KEY_DEFAULT);// 获取第一个扇区权限
		    if (auth) {
			byte[] date = mf.readBlock(0);// 读取block 0
			RFID = CHexConver.bytesToHexStrings(date);
			Message msg = MyHandler.obtainMessage();
			msg.what = 1;
			msg.obj = RFID;
			MyHandler.sendMessage(msg);
		    }

		} catch (IOException e) {

		    e.printStackTrace();
		} finally {
		    try {
			mf.close();
		    } catch (IOException e) {

			e.printStackTrace();
		    }
		}

	    }
	    NfcV nf = NfcV.get(tagFromIntent);
	    if (nf != null) {
		RFID = CHexConver.bytesToHexStrings(nf.getTag().getId());
		Message msg = MyHandler.obtainMessage();
		msg.what = 1;
		msg.obj = RFID;
		MyHandler.sendMessage(msg);
	    }

	}

	super.onNewIntent(intent);
    }

    /**
     * 初始化定位
     */
    public void initlocation() {

	client = new LocationClient(this);
	LocationClientOption option = new LocationClientOption();
	// 打开GPS
	option.setOpenGps(true);

	// 设置坐标类型
	option.setCoorType("bd09ll");

	// 设置网络优先

	option.setPriority(LocationClientOption.GpsFirst);

	// 设置产品线名称
	option.setProdName("waterSys");
	option.disableCache(true);// 禁止启用缓存定位
	// 设置定位定时时间
	option.setScanSpan(10000);
	client.setLocOption(option);
	client.registerLocationListener(this);

    }

    @Override
    public void onReceiveLocation(BDLocation location) {
	GPS(location);
    }

    @Override
    public void onReceivePoi(BDLocation arg0) {

    }

    /**
     * 判断GPS是否存在或开启
     */
    public boolean openGPSSettings() {
	LocationManager alm = (LocationManager) getSystemService(this.LOCATION_SERVICE);
	if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
	    return true;
	}
	Toast.makeText(this, "请开启GPS！", Toast.LENGTH_SHORT).show();
	Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
	startActivityForResult(intent, 0); // 此为设置完成后返回到获取界面
	return false;
    }

    /**
     * 得到定位数据
     * 
     * @param location
     */
    public void GPS(BDLocation location) {
	boolean b = openGPSSettings();
	if (!b) {
	    return;
	}
	if (location != null) {
	    if (location.getLocType() == 61) {
		client.stop();
		textview6.setText("纬度:" + location.getLatitude());
		textview7.setText("经度：" + location.getLongitude());
		latitude = location.getLatitude();
		longitude = location.getLongitude();
		Toast.makeText(this, "定位成功" + location.getLocType(), Toast.LENGTH_LONG).show();
		TipHelper.Vibrate(this, 1000);
		sp.insertValue(XmlNameHelper.GPSLATITUDE, location.getLatitude() + "");
		sp.insertValue(XmlNameHelper.GPSLONGITUDE, location.getLongitude() + "");
		sp.insertValue(XmlNameHelper.GPSDATE, System.currentTimeMillis() + "");

	    } else if (location.getLocType() == 161) {

		client.stop();
		showDialog();
		TipHelper.Vibrate(this, 1000);

	    }
	}
    }

    public void showDialog() {

	String message = "";
	if (sp.getValue(XmlNameHelper.GPSDATE).equals("0")) {
	    message = "还没有定位成功过！";
	} else {
	    long ti = System.currentTimeMillis() - Long.parseLong(sp.getValue(XmlNameHelper.GPSDATE));

	    message = "最近一次定位时间在:" + DateUtil.getMuntion(ti);
	}

	Builder builder = new android.app.AlertDialog.Builder(this);
	// 设置对话框的图标
	builder.setIcon(R.drawable.buttondraw);
	// 设置对话框的标题

	builder.setMessage(message);

	// 添加一个确定按钮
	builder.setPositiveButton(" 确 定 ", new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int which) {
		textview6.setText("纬度:" + sp.getValue(XmlNameHelper.GPSLATITUDE));
		textview7.setText("经度：" + sp.getValue(XmlNameHelper.GPSLONGITUDE));
		latitude = Double.parseDouble(sp.getValue(XmlNameHelper.GPSLATITUDE));
		longitude = Double.parseDouble(sp.getValue(XmlNameHelper.GPSLONGITUDE));

	    }
	});
	builder.setNeutralButton("取消", new DialogInterface.OnClickListener() {

	    @Override
	    public void onClick(DialogInterface dialog, int which) {
		textview6.setText("纬度:" + 0.0);
		textview7.setText("经度：" + 0.0);
		latitude = 0.0;
		longitude = 0.0;

	    }
	});
	// 创建一个单选按钮对话框
	dialog = builder.create();
	dialog.show();

    }
}
